package com.qty.apkviewer.adapter

import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.qty.apkviewer.R
import com.qty.apkviewer.model.ApkInfo

class ApkViewerAdapter(val context: Context, var apks: ArrayList<ApkInfo>): BaseAdapter() {

    fun setApkInfos(infos: ArrayList<ApkInfo>) {
        apks = infos
        notifyDataSetChanged()
    }

    override fun getCount(): Int {
        return apks.size
    }

    override fun getItem(position: Int): ApkInfo {
        return apks.get(position)
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view: View = convertView ?: LayoutInflater.from(context).inflate(R.layout.apk_viewer_list_item, parent, false)

        if (convertView == null ) {
            val iconIv = view.findViewById<ImageView>(R.id.icon)
            val nameTv = view.findViewById<TextView>(R.id.name)
            val packageNameTv = view.findViewById<TextView>(R.id.package_name)
            val mainClassNameTv = view.findViewById<TextView>(R.id.main_class_name)
            view.tag = ViewHolder(iconIv, nameTv, packageNameTv, mainClassNameTv)
        }
        val holder = view.tag as ViewHolder
        val apkInfo = getItem(position)
        holder.iconIv.setImageDrawable(apkInfo.icon)
        holder.nameTv.text = apkInfo.name
        holder.packageNameTv.text = apkInfo.packageName
        if (TextUtils.isEmpty(apkInfo.mainClassName)) {
            holder.mainClassNameTv.visibility = View.GONE
        } else {
            holder.mainClassNameTv.text = apkInfo.mainClassName
            holder.mainClassNameTv.visibility = View.VISIBLE
        }
        return view
    }

    data class ViewHolder(
        val iconIv: ImageView,
        val nameTv: TextView,
        val packageNameTv: TextView,
        val mainClassNameTv: TextView
    )
}